package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"news/common"
	"news/models"
	"time"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Register() {
	Username := c.GetString("username")
	Password := c.GetString("password")

	user := models.User{
		Username: Username,
		Password: common.Md5Password(Password),
	}

	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "注册成功",
			Data: user,
		}
		c.ServeJSON()
	}
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	key := "lock-" + username
	count, _ := models.Rdb.Get(key).Int()

	if count >= 3 {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "账号已冻结,请两小时后重试",
			Data: nil,
		}
		c.ServeJSON()
	}

	var user models.User
	err := models.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "用户名不存在",
			Data: nil,
		}
		c.ServeJSON()
		if user.Password == common.Md5Password(password) {
			c.Data["json"] = JsonR{
				Code: 0,
				Msg:  "登陆成功",
				Data: user,
			}
			c.ServeJSON()
		}

	} else {
		models.Rdb.Incr(password)
		models.Rdb.Expire(key, time.Hour*2)
		c.Data["json"] = JsonR{
			Code: 0,
			Msg:  "密码错误",
			Data: nil,
		}
		c.ServeJSON()
	}
}
